﻿Feature = function (endPoint, baseUrl) {
    this.endPoint = endPoint;
    this.baseUrl = baseUrl;
}


Feature.prototype = {
    ExecuteRequest: function (url, postData, method, callback, params) {

        var xmlhttp = null;

        try {
            if (!(this.baseUrl == undefined || this.baseUrl == ""))
                url = this.baseUrl + "/" + this.endPoint;
            else
                url = this.endPoint;

            if (window.XMLHttpRequest)
                xmlhttp = new XMLHttpRequest();
            else if (window.ActiveXObject) {
                if (new ActiveXObject("Microsoft.XMLHTTP"))
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                else
                    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            if (method == undefined || null == method)
                method = 'POST';

            if (null != callback && callback != undefined) {
                this.async = true;
                xmlhttp.open(method, url, true); //false - синхронный
                xmlhttp.onreadystatechange = function () { return callback(xmlhttp, params); };

            }
            else {
                this.async = false;
                xmlhttp.open(method, url, false); //false - синхронный

            }
            xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            xmlhttp.setRequestHeader("Cache-Control", "no-cache");
            xmlhttp.setRequestHeader("Pragma", "no-cache");

            if (method == 'GET') {
                xmlhttp.setRequestHeader("x-vs-parameters", postData);
                xmlhttp.send(null);
            }
            else {

                xmlhttp.send(postData);
            }

            if (this.async != false)
                return;

            var responseText = xmlhttp.responseText;
        }
        catch (e) {
            this.OnError(xmlhttp, e);
        }

        if (xmlhttp.status == 12030) {
            alert('Время жизни страницы истекло. Попробуйте перезагрузить страницу.')
            return;
        }

        if (xmlhttp.status != 200)

            this.OnError(xmlhttp);

        return responseText;

    },

    isJson: function (responseText) {
        var expr = new RegExp('^{');
        return expr.test(responseText);

    },
    ParseResponse: function (responseText) {
        if (undefined == responseText || null == responseText)
            return null;

        if (!this.isJson(responseText)) {
            alert('Страница - устарела. Попробуйте перегрузить страницу.');
            return null;
        }

        var resp = Ext.decode(responseText);
        if (null == resp)
            return resp;

        if (undefined == resp.success || resp.success == false || undefined == resp.result) {
            this.OnError(resp);
            return null;
        }
        return resp.result;
    },

    Request: function (url, postData, method, callback, params) {
        var resp = this.ExecuteRequest(url, postData, method, callback, params);
        return this.ParseResponse(resp);
    },

    Execute: function (cmd, resourceUrl, callback, params) {
        return this.Request(resourceUrl, null == cmd || cmd == undefined ? null : Ext.encode(cmd), 'POST', callback, params);
    },

    ExecuteNoParse: function (resourceUrl, args, callback, params) {
        return this.ExecuteRequest(resourceUrl + '.cmd', null == args || args == undefined ? null : JSON.stringify(args), 'POST', callback, params);
    },

    // resp - ответ сервера
    // e- Error или FeatureExecutionResult.Errors[]
    OnError: function (resp, e) {
        var msg = '';

        if (undefined != e && null != e && undefined != e.message)

            msg += 'При вызове службы сервера произошла ошибка! ' + e.message;

        if (undefined == resp || null == resp)
            throw new Error(msg);

        if (undefined != resp.result)
            msg += Ext.encode(resp.result) + '.';
        else
            msg += resp.responseText;

        this.DisplayError(msg);
    },

    DisplayError: function (msg) {
        throw new Error(msg);
    }
}


